from flask import Blueprint, jsonify, request
from conf.comm import sqlalchemy_context
from database import *
import json

# 实例化
bp_course = Blueprint('course', __name__)

#无限极分类构造
def xtree(data):
    list = []
    tree = {}
    if data:
        #先解析成字典
        for i in data:
            tree[i['id']] = i

        for j in data:
            #判断是否有父类==0代表是父类加入列表
            if j['parent'] == 0:
                list.append(j)
            else:
                #有父类
                #看父类下是否有子类，如果有，append添加，没有就初始化
                if 'son' not in tree[j['parent']]:
                    tree[j['parent']]['son'] = []
                    #把子类加到特定的父类下
                tree[j['parent']]['son'].append(j)
        return list
    else:
        return data


# 添加分类
@bp_course.route('/cateM', methods=['POST', 'GET'])
@sqlalchemy_context()
def cateM():
    if request.method == 'POST':
        try:
            data = request.data
            if data:
                data = json.loads(data)
            else:
                data = request.form
            cate = Cate(name=data['name'], parent=data['parent'], level=data['level'], params=data['params'])
            db.session.add(cate)
            db.session.commit()
            return jsonify({'code': 200})
        except:
            return jsonify({'code': 10010})
    else:
        # 获取所有的分类
        list = []
        cates = Cate.query.all()
        if cates:
            for i in cates:
                dict = {'id': i.id, 'name': i.name, 'parent': i.parent, 'params': i.params, 'level': i.level}
                list.append(dict)
        list1 = xtree(list)
        return jsonify({'code': 200, "list": list1})
